const https = require('https');

const weiboinfo = {
	APP_ID: "2486615185",
	APP_KEY: "f05e881cedb57d65b57537b07ca4fdf9",
	REDIRECT_URI: "http://editor.makelouden.cc/user/setToken/weibo"
}

const setToken = (req, res, cb) => {
	/*
	http://editor.makelouden.cc/user/setToken/qq?code=106F95F473BF91CF118C5903DE2583EC&state=vJRzivds2C7BzUTEd6ZyOY2i5-DLsq8g
	*/
	var code = req.query.code;
	var path = "/oauth2/access_token?client_id=" + weiboinfo.APP_ID + "&client_secret=" + weiboinfo.APP_KEY + "&grant_type=authorization_code&redirect_uri=" + weiboinfo.REDIRECT_URI + "&code=" + code;
	// console.log(path);

	var options = {
		hostname: "api.weibo.com",
		port: 443,
		method: 'POST',
		path: path,
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		}
	};

	let req1 = https.request(options, (res1) => {
		// console.log('statusCode:', res1.statusCode);
		// console.log('headers:', res1.headers);
		res1.on('data', (d) => {
			// console.log('BODY: ' + d);
			d = JSON.parse(d);

			let getUserInfo = () => {
				var path = "/2/users/show.json?access_token=" + d.access_token + "&uid=" + d.uid;
				// console.log(path);
				options = {
					hostname: "api.weibo.com",
					port: 443,
					method: 'GET',
					path: path
				};
				var req2 = https.request(options, (res2) => {
					res2.on('data', (d2) => {
						d2 = JSON.parse(d2);
						// console.log('BODY2: ' + d2);
						var sessionStore = req.sessionStore;
						var sid = req.query.state;
						sessionStore.load(sid, (err, sess) => {
							if (err) {

								res.redirect(301, '/close.html');
								console.error(err);
							} else if (!sess) {
								res.redirect(301, '/close.html');
								// return;
							} else if (d2.errcode) {
								// console.log(d2);
								res.send(JSON.stringify({
									result: -1,
									msg: "登陆错误，请重试",
									// error: error
								}));
								console.error(errcode);
							} else {
								sess.userInfo = {
									userType: "weibo",
									id: "weibo_" + d2.idstr,
									nickname: d2.screen_name,
									verified: true,
									prop: d2
								};
								sess.save((err) => {
									console.error(err);
								});
								res.redirect(301, '/close.html');
								// console.log("set token " + sess.id);
								// console.log(sess);
								cb(sess.userInfo);
							}
						});
					});
				});


				req2.on('error', (err) => {
					// console.error(e);
					res.send(JSON.stringify({
						result: -1,
						msg: "获取用户信息出错",
						// error: e
					}));
					// return;
					console.error(err);
				});
				req2.end();
			}
			getUserInfo();
		});
	});

	req1.on('error', (err) => {
		// console.error(e);
		res.send(JSON.stringify({
			result: -1,
			msg: "登陆错误，请重试",
			// error: e
		}));
		// return;
		console.error(err);
	});
	req1.end();
};
module.exports.setToken = setToken;